<template>
  <div class="U000002-template1" :style="box_style" :class="className">
    <!-- style -->
    <div v-html="css"></div>
    <img v-if="list.length == 0" :style="wrapper_style" :src="defaultUrl" alt="">
    <div v-if="list.length == 1 && ((datas.swiper_effect && datas.swiper_effect == 1) || !datas.swiper_effect)" :style="wrapper_style">
      <img :style="img_style" :src="list[0].image" alt="" @click="toUrl(list[0])">
      <div style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;"
           v-if="list[0].is_minApp == 2 && !fun.isApp() && !fun.isCPS()" @click.stop v-html="list[0].html">
      </div>
      <template v-if="list[0].child_choose_style == '3' &&list[0].hotArea && list[0].hotArea.length > 0">
        <div
          class="hotarea-rnd"
          v-for="(area, index) in list[0].hotArea"
          :style="{
            top: area.top * (clientWidth / 400) + 'px',
            left: area.left * (clientWidth / 400) + 'px',
            width: area.width * (clientWidth / 400) + 'px',
            height: area.height * (clientWidth / 400) + 'px'
          }"
          :key="index"
          @click="toAreaUrl(area)"
        >
          <div style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" v-if="area.is_minApp == 2 && !fun.isApp() && !fun.isCPS()" @click.stop v-html="area.html"></div>
        </div>
      </template>
    </div>
    <van-swipe class="my-swipe slideshow" :autoplay="3000" :indicator-color="datas.slides_active_color || '#1989fa'" v-if="list.length > 1 && ((datas.swiper_effect && datas.swiper_effect == 1) || !datas.swiper_effect)" ref="mySwiper">
      <!-- slides -->
      <van-swipe-item v-for="(item, idx) in list" :key="idx">
        <div class="list-image" v-if="item.image" :style="wrapper_style">
          <div style="position: relative;" :style="img_style">
            <img :src="item.image" alt="" :style="img_style" @click="toUrl(item)">
            <template v-if="item.child_choose_style == '3' &&item.hotArea && item.hotArea.length > 0">
              <div
                class="hotarea-rnd"
                v-for="(area, index) in item.hotArea"
                :style="{
                  top: area.top * (clientWidth / 400) + 'px',
                  left: area.left * (clientWidth / 400) + 'px',
                  width: area.width * (clientWidth / 400) + 'px',
                  height: area.height * (clientWidth / 400) + 'px'
                }"
                :key="index"
                @click="toAreaUrl(area)"
              >
                <div style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" v-if="area.is_minApp == 2 && !fun.isApp() && !fun.isCPS()" @click.stop v-html="area.html"></div>
              </div>
            </template>
          </div>
          <div style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;"
               v-if="item.is_minApp == 2 && !fun.isApp() && !fun.isCPS()" @click.stop v-html="item.html">
          </div>
        </div>
      </van-swipe-item>
      <!--分页-->
      <!-- <div class="swiper-pagination" slot="pagination"></div> -->
    </van-swipe>

    <div class="picture_even_main" :style="wrapper_style" v-if="datas.swiper_effect && datas.swiper_effect == 2">
      <div v-for="(item, idx) in list" :key="idx" class="picture_even_item">
        <img :src="item.image" alt="" @click="toUrl(item)">
        <div style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;"
          v-if="item.is_minApp == 2 && !fun.isApp() && !fun.isCPS()" @click.stop v-html="item.html">
        </div>
      </div>
  </div>
  </div>
</template>

<script>
import defaultUrl from "@/assets/images/new_diy/banner.png";

// 自定义样式
const css = function() {
  if (this.datas.picture_even_height) {
    const { picture_even_height, picture_border, picture_even_margin } = this.datas;

    return `
      .component-${this.id} .picture_even_main{
          height: ${picture_even_height}px;
      }
      .component-${this.id} .picture_even_main img{
          border-radius: ${picture_border}px;
          margin-right: ${picture_even_margin}px;
      }
  `;
  }
};

export default {
  props: ['id', 'datas', 'styles'],
  data () {
    return {
      clientWidth: '375',
      // 轮播图设置
      swiperOption: {
        autoplay: true,
        // loop: true,   loop模式第二轮循环的时候第一张会闪烁
        delay: 3000,
        observer:true,
        // autoHeight: true,
        pagination: {
          el: '.swiper-pagination',
        }
      },
      defaultUrl
    };
  },

  components: {},

  computed: {
    css() {
      return "<style>" + css.call(this) + "</style>";
    },
    className() {
      const name = ["component-wrapper", `component-${this.id}`];
      return name;
    },
    // 初始化
    swiper () {
      return this.$refs.mySwiper.swiper;
    },

    /** 样式 */
    wrapper_style() {
      const {
        padding_top,
        padding_bottom,
        padding_left,
        padding_right,
      } = this.datas;
      return `
                width: 100%;
                padding-top: ${padding_top}px;
                padding-bottom: ${padding_bottom}px;
                padding-left: ${padding_left}px;
                padding-right: ${padding_right}px;
                position: relative;
            `;
    },

    img_style() {
      const {
        picture_border,
      } = this.datas;
      return `
                border-radius: ${picture_border}px;
            `;
    },

    box_style() {
      const {
        slides_default_color,
        preview_color={},
        bg_color = null,
      } = this.datas;
      return `
                --slides_default_color: ${slides_default_color || '#333333'};
				        background-color: ${preview_color.color || bg_color || '#ffffff'};
                background-image: url(${preview_color.isColor == 2 ? preview_color.image || emptyImage : ""});
                background-size: 100% 100%;
                background-position: center;
                background-repeat: no-repeat;
            `;
    },

    // 广告轮播列表
    list () {
      try {
        let list = [...this.datas.list] || [];
        list = list.filter(item => item.image != '');
        return list;
      } catch (err) {
        return [];
      }
    }
  },
  mounted () {
    this.$nextTick(()=>{
      this.initButtons();
    });
  },
  activated() {
    this.$nextTick(()=>{
      this.initButtons();
    });
  },
  methods: {
    toUrl(item) {
      if(item.is_minApp == 2 && this.fun.isApp()) {
        YDB.MiniWX(item.gh_id, item.minApp_link);
        return;
      }
      if(item.is_minApp == 2 &&  this.fun.isCPS()) {
        let json = {
          mini_route: item.minApp_link,
          mini_id: item.gh_id,
        };
        if (this.fun.isIosOrAndroid() === "ios") {
          miniWXIOS({ body: "miniWXIOS", json: JSON.stringify(json) });
        } else {
          miniWXAndroid(JSON.stringify(json));
        }
        return;
      }

      if(item.is_minApp == 1 && item.h5_link) {
        let URL = this.fun.deeplinkURL(item.h5_link) + 't=' + Math.random();
        window.location.href = URL;
      }

      if (item.is_minApp == 9 && this.fun.isCPS() && this.fun.isCPSAPPI()) {
        // 跳转聚合APP链接
        let { app_path, pathParam, ...otherParam} = this.queryStringToObject(item.cps_link);
        let json = {
          ...otherParam,
          'target': {
            'app_path': app_path,
            'path_param': pathParam,
            "keyword": "",
            "app_route": "",
            "web_title": "",
            "web_url": "",
            "mini_route": "",
            "mini_id": "",
            "brand_id": 0,
            "brand_goods_id": 0,
            "another_plat": 0,
            "activity_info": "",
            "list_id": "",
            "list_type": "",
            "album_type": "",
            "album_id": ""
          }
        };
        if (this.fun.isIosOrAndroid() === "ios") {
          toAPPUrlIOS({ body: "toAPPUrlIOS", json: JSON.stringify(json) });
        } else {
          toAPPUrlAndroid(JSON.stringify(json));
        }
        return;
      }
    },

    queryStringToObject(queryString) {
      // 处理cps app路径，解码并分割字符串
      const params = queryString.split('&');
      const obj = {};
      params.forEach(param => {
        // 分割键和值
        const [key, value] = param.split('=');
        // 解码URL编码
        obj[decodeURIComponent(key)] = decodeURIComponent(value);
      });
      return obj;
    },
    // 图片加载完回调
    getImg(url, callback) {
      let img = new Image();
      img.src = url;
      //如果图片被缓存，则直接返回缓存数据
      if (img.complete) {
        /* callback(img.width, img.height); */
        callback(Number(img.height) / Number(img.width));
      } else {
        //完全加载完毕的事件
        img.onload = function() {
          /* callback(img.width, img.height); */
          callback(Number(img.height) / Number(img.width));
        };

        img.onerror = function() {
          console.log('图片加载出错');
        };
      }
    },
    initButtons() {
      let that = this;
      if(this.fun.getPhoneEnv() == 3) {
        this.clientWidth = 375;
      }else {
        this.clientWidth = document.body.clientWidth;
      }

      for(let j=0; j<this.datas.list.length; j++) {
        if(this.datas.list[j].image) {
          this.getImg(this.datas.list[j].image, function(scale) {
            // 图片加载完后获取图片高度
            let script = document.createElement('script');
            script.type = 'text/wxtag-template';
            script.text = `<div style="width: ${that.clientWidth}px;height: ${that.clientWidth*scale}px;"></div>`;
            that.datas.list[j].html = `<wx-open-launch-weapp username="${that.datas.list[j].gh_id}" path="${that.datas.list[j].minApp_link}">${script.outerHTML}</wx-open-launch-weapp>`;

            that.datas.list.reverse().reverse(); //改变原始数组从而更新数组
          });
        }
      }

    },

        toAreaUrl(item) {
      let URL = '';
      if(item.is_minApp == 2 && this.fun.isApp()) {
        YDB.MiniWX(item.gh_id, item.minApp_link);
        return;
      }
      if(item.is_minApp == 2 &&  this.fun.isCPS()) {
        let json = {
          mini_route: item.minApp_link,
          mini_id: item.gh_id,
        };
        if (this.fun.isIosOrAndroid() === "ios") {
          miniWXIOS({ body: "miniWXIOS", json: JSON.stringify(json) });
        } else {
          miniWXAndroid(JSON.stringify(json));
        }
        return;
      }

      if(item.is_minApp == 7) {
        if (this.fun.isCPS() && this.fun.isCPSAPPI()) {
          let json = { name: 'task' };
          if (this.fun.isIosOrAndroid() === "ios") {
            toUrlIOS({ body: "toUrlIOS", json: JSON.stringify(json) });
          } else {
            toUrlAndroid(JSON.stringify(json));
          }
        }else if(item.h5_link) {
          URL = this.fun.deeplinkURL(item.h5_link);
          if(this.$route.query.device_no){ //生态圈饮水机-设备号
            URL+="&device_no="+this.$route.query.device_no
          }else if(window.localStorage.getItem('device_no')){
            URL+="&device_no="+window.localStorage.getItem('device_no');
          }
          window.location.href = URL;
        }
      }else if (item.is_minApp == 1 && item.h5_link) {
        URL = this.fun.deeplinkURL(item.h5_link);
        if(this.$route.query.device_no){ //生态圈饮水机-设备号
          URL+="&device_no="+this.$route.query.device_no
        }else if(window.localStorage.getItem('device_no')){
          URL+="&device_no="+window.localStorage.getItem('device_no');
        }

        window.location.href = URL;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
  .U000002-template1 {
    display: block;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
    width: 100%;
    overflow: hidden;

    img {
      width: 100%;
      display: block;
      border: none;
    }
  }

  .slideshow ::v-deep .van-swipe__indicator {
    background-color: var(--slides_default_color);
  }

  .picture_even_main {
    display: flex;
    -ms-overflow-style: none;  /* IE and Edge */
    scrollbar-width: none;     /* Firefox */
    &::-webkit-scrollbar {
      display: none;           /* Chrome, Safari, Opera*/
    }
    overflow-x: scroll;
    overflow-y: hidden;
    .picture_even_item {
      display: flex;
      height: 100%;
      flex-shrink: 0;
      position: relative;
    }
    img {
        height: 100%;
        width: auto;
        display: block;
        margin: 0;
    }
}
.hotarea-rnd {
  position: absolute;
  user-select: auto;

  display: inline-block;
  top: 5px;
  left: 5px;
  width: 60px;
  height: 50px;
  padding: 5px 10px;
  box-sizing: border-box;

  // border: 1px solid #29ba9c;
  // background: rgba(41, 186, 156, 0.3);

  font-size: 12px;
  color: #fff;
}
</style>
